<?php
namespace App\Http\Common;
use App\Models\BaseHard;
use App\Models\Csyys\Order;
use App\Models\Csyys\OrderHistory;
use App\Models\Front\Bill;
use App\Models\Front\UserWyWechatAccount;
use App\Models\Houswholds;
use App\Models\InBillHistory;
use App\Models\WyBill;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;

/**
 * 账单的生成
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019-08-14
 * Time: 21:35
 */
class OrderDeal{
    //创建静态私有的变量保存该类对象
     static private $instance;
     //参数
     private $config;
     //防止直接创建对象
     private function __construct($config){
         $this -> config = $config;
     }
      //防止克隆对象
     private function __clone(){
     }
     // 使用单列模式
     static public function getInstance($config=null){
         //判断$instance是否是Uni的对象
         //没有则创建
        if (!self::$instance instanceof self) {
            self::$instance = new self($config);
        }
        return self::$instance;
    }

    /**
     * 付钱1 写到 数据库 bf_wy_order里面
     * goods_price 钱
     * type 订单 类型
     * @return mixed
     */
    public function generateOrder1($request)
    {
        // 用户id
        $userId = MyUtils::getSessionIdKeep($request,'user_id');
        $base = new BaseHard();
        $order['order_number'] = $base->getUniqueCode(Order::class,"order_number");
        $order['business_id'] = MyUtils::sg($request,"business_id");
        $order['user_id'] = $userId;
        $order['type'] = MyUtils::sg($request,"type",2);//默认是商家订单
        $order['order_status'] = MyUtils::sg($request,"order_status",1);
        $order['goods_price'] = MyUtils::sg($request,"goods_price");
        $order['address_id'] = MyUtils::sg($request,"address_id");
        $order['self_get'] = MyUtils::sg($request,"self_get",1);
        $order['self_get_time'] = MyUtils::sg($request,"self_get_time");
        $order['wy_operator_id'] = MyUtils::getSessionIdKeep($request,"wy_operator_id");
        $order['remark'] = MyUtils::getSessionIdKeep($request,"remark");
        $order['common_order_number'] = MyUtils::getSessionIdKeep($request,"common_order_number");
        $res3 = Order::insertGetId(MyUtils::getDbKnowArray($order));
        if (!$res3){
            Globals::$error = "生成订单失败，请重新生成！";DB::rollBack();
            return false;
        }
        // 生成历史订单记录
        $order['order_id'] = $res3;
        Session::put("order_id",$res3);// 保存订单id,为后面使用
        unset($order['id']);
        $res5 = OrderHistory::insertGetId($order);
        if (!$res5){
            Globals::$error = "生成订单历史记录失败，请重新生成！";DB::rollBack();
            return false;
        }
        // 处理完成 ，记录，写进埋点，
        if ($res3){
            activity()
                ->performedOn(Order::find($res3))
                ->causedBy($userId)
                ->inLog(MyUtils::getActivityLogType())
                ->log('生成收费订单');
        }
        return $res3;
    }


    /**
     * 付钱2 写到 数据库 bf_wy_bills里面
     * @param $request
     * @param $className
     * @return mixed
     */
    public function generateOrder2($request,$className)
    {
        $id = MyUtils::sg($request,"id");//维修列表的id
        $code = (new BaseHard())->getUniqueCode(Bill::class);// 订单编号
        // 用户id
        $userId = MyUtils::getSessionIdKeep($request,'manager_user_id');
        $re = MyUtils::getDbKnowArray($request);
        $dealMoney =  MyUtils::sg($re,'deal_money');
        $repairModel = $className::where('id',$id)->get("*")->first();
        $bill['deal_status'] = MyUtils::sg($request,"deal_status");
        $bill['wy_room_id'] = MyUtils::sg($repairModel,"wy_room_id");
        $bill['wy_area_id'] = MyUtils::sg($repairModel,"wy_area_id");
        $bill['code'] = $code;
        $bill['name'] = '维修账单';
        $bill['start_time'] = MyUtils::sg($repairModel,"created_at");
        $bill['end_time'] = DayTimes::getInstance()->now();
        $bill['price'] = $dealMoney;
        $bill['number'] = 1;
        $bill['should_in'] = $dealMoney;
        $bill['remark'] = MyUtils::sg($repairModel,"remark");
        $bill['if_payment'] = -1;//是否缴纳(是/否) 1是 -1否
        $bill['type'] = 2;//类型： 1物业费，2维修费，3报修费...4维护,5电费,6水费,7人员工资
        $bill['wy_houswhold_id'] = MyUtils::sg($repairModel,"wy_houswhold_id");//所属的住户的id
        $bill['in_out'] = 1;//收入还是支出   1收入 -1支出
        $bill['url'] = MyUtils::sg($repairModel,"url");//url附件
        $bill['project_id'] = MyUtils::getSessionConfig("PROJECT_ID");
        $bill['bill_deal_wy_user_id'] = MyUtils::getSessionId($request,"manager_user_id");//订单处理人
        $bill['bill_wy_user_id'] = MyUtils::sg($repairModel,"wy_user_id");// 订单 所属人
        $res3 = Bill::insertGetId(MyUtils::getDbKnowArray($bill));
        if (!$res3){
            Globals::$error = "生成订单失败，请重新生成！";DB::rollBack();
            return false;
        }
        // 生成历史订单记录
        $bill['wy_bill_id'] = $res3;
        unset($bill['id']);
        $res5 = InBillHistory::insertGetId(MyUtils::getDbKnowArray($bill));
        if (!$res5){
            Globals::$error = "生成订单历史记录失败，请重新生成！";DB::rollBack();
            return false;
        }
        // 推送模板消息，通知用户应该交钱
        $bill = WyBill::where("id",$res3)->first();
        // 查询相应的户主的id
        $wyHouswhold = Houswholds::where("id",$bill->wy_houswhold_id)->get("*")->first();
        if (!$wyHouswhold){
            Globals::$error = "该住户已经不存在，已经删除或者其他原因！";
            return false;
        }
        // 拿到微信账号 的openId
        $wyUserId = MyUtils::sg($wyHouswhold,'wy_user_id');// 用户id
        $totalFee = round(MyUtils::sg($bill,'should_in')/100,2);// 账单总额
        $request->ids = [$res3];
        if ($wyHouswhold){
            $roomArea = GroupTools::getInstance()->getRoomArea($bill->wy_room_id);
            // 物业账单通知
            WeChatApp::getPublicInstance()->sendPublicTmplateMessage('OPENTM418048015',[
                    'first'=>'您的'.$bill->name.'的物业账单',
                    'keyword1'=>$wyHouswhold->name, // 业主姓名
                    'keyword2'=>$roomArea,//产权地址
                    'keyword3'=>$totalFee.'元',
                    'remark'=>'点击详情，可查看账单明细详情，如有疑问请联系物业处。',
                ],
                $wyUserId,'user_id'
            ,$bill);
        }
        // 处理完成 ，记录，写进埋点，
        if ($res3){
            activity()
                ->performedOn(Bill::find($res3))
                ->causedBy($userId)
                ->inLog(MyUtils::getActivityLogType())
                ->log('生成收费订单');
        }
        return $res3;
    }


    /**
     * 回收垃圾生成账单 写到 数据库 bf_wy_bills里面
     * @param $request
     * @param $className
     * @return mixed
     */
    public function generateOrder3($request,$className)
    {
        $baseHard = new BaseHard();
        $code = $baseHard->getUniqueCode(Bill::class);// 订单编号
        // 用户id
        $userId = MyUtils::getSessionIdKeep($request,'manager_user_id');
        $model = $className::where('id',$request->id)->get("*")->first();
        $billModel = new Bill();
        $billModel->deal_status = $model->deal_status;
        $billModel->wy_room_id = $model->wy_room_id;
        $billModel->wy_area_id = $model->wy_area_id;
        $billModel->code = $code;
        $billModel->name = '回收账单';
        $billModel->start_time = $model->created_at;
        $billModel->end_time = DayTimes::getInstance()->now();
        $billModel->should_in = $request->deal_money;
        $billModel->remark = $model->remark;
        $billModel->if_payment = -1;//是否缴纳(是/否) 1是 -1否
        $billModel->type = 9;//类型： 1物业费，2维修费，3报修费...4维护,5电费,6水费,7人员工资
        $billModel->wy_houswhold_id = $model->wy_houswhold_id;//所属的住户的id
        $billModel->in_out = -1;//收入还是支出   1收入 -1支出
        $billModel->url = $model->url;//url附件
        $billModel->project_id = MyUtils::getSessionConfig("PROJECT_ID");
        $billModel->bill_deal_wy_user_id = MyUtils::getSessionId($request,"manager_user_id");//订单处理人
        $billModel->bill_wy_user_id = $model->wy_user_id;// 订单 所属人
        $billModel->project_id = MyUtils::getSessionConfig("PROJECT_ID");// 订单 所属人
        $res3 = $billModel->save();
        if (!$res3){
            Globals::$error = "生成订单失败，请重新生成！";DB::rollBack();
            return false;
        }
        // 查询相应的户主的id
        $wyHouswhold = Houswholds::where("id",$billModel->wy_houswhold_id)->get("*")->first();
        if (!$wyHouswhold){
            Globals::$error = "该住户已经不存在，已经删除或者其他原因！";
            return false;
        }
        // 拿到微信账号 的openId
        $wyUserId = $wyHouswhold->wy_user_id;// 用户id
        $totalFee = round($billModel->should_in/100,2);// 账单总额
        if ($wyHouswhold){
            $roomArea = GroupTools::getInstance()->getRoomArea($billModel->wy_room_id);
            // 物业账单通知
            WeChatApp::getPublicInstance()->sendPublicTmplateMessage('OPENTM418048015',[
                'first'=>'您的'.$billModel->name.'的回收账单',
                'keyword1'=>$wyHouswhold->name, // 业主姓名
                'keyword2'=>$roomArea,//产权地址
                'keyword3'=>$totalFee.'元',
                'remark'=>'点击详情，可查看账单明细详情，如有疑问请联系物业处。',
            ],
                $wyUserId,'user_id'
            );
        }
        // 处理完成 ，记录，写进埋点，
        activity()
            ->performedOn($billModel)
            ->causedBy($userId)
            ->inLog(MyUtils::getActivityLogType())
            ->log('生成回收账单');
        return $billModel;
    }



}
